document.addEventListener('DOMContentLoaded', function() {
    // 设置容量条颜色
    const capacityFills = document.querySelectorAll('.capacity-fill');
    capacityFills.forEach(fill => {
        const width = parseFloat(fill.style.width);
        if (width >= 90) {
            fill.classList.add('capacity-critical');
        } else if (width >= 70) {
            fill.classList.add('capacity-warning');
        } else {
            fill.classList.add('capacity-good');
        }
    });
    
    // 标签切换
    const tabBtns = document.querySelectorAll('.tab-btn');
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除所有活动状态
            tabBtns.forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
            
            // 添加当前活动状态
            btn.classList.add('active');
            const tabId = btn.getAttribute('data-tab') + '-tab';
            document.getElementById(tabId).classList.add('active');
        });
    });
    
    // 存储消息表单提交
    const storeForm = document.getElementById('store-message-form');
    if (storeForm) {
        storeForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const content = document.getElementById('message-content').value;
            const password = document.getElementById('message-password').value;
            const lockerId = storeForm.querySelector('input[name="locker_id"]').value;
            
            // 验证密码
            if (!/^\d{6}$/.test(password)) {
                showError(storeForm, '密码必须是6位数字');
                return;
            }
            
            // 显示加载状态
            const submitBtn = storeForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 存储中...';
            
            try {
                const response = await fetch('/create_in_locker', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        content: content,
                        password: password,
                        locker_id: lockerId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 显示成功信息
                    document.getElementById('result-message-id').textContent = data.message_id;
                    document.getElementById('result-locker-id').textContent = data.locker_id;
                    document.getElementById('result-locker-name').textContent = data.locker_name;
                    
                    // 隐藏表单，显示结果
                    document.querySelector('.locker-tabs').classList.add('hidden');
                    document.getElementById('store-result-card').classList.remove('hidden');
                } else {
                    showError(storeForm, data.error || '存储消息失败，请重试');
                }
            } catch (error) {
                showError(storeForm, '发生错误，请重试');
                console.error('Error:', error);
            } finally {
                // 重置按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            }
        });
    }
    
    // 获取消息表单提交
    const retrieveForm = document.getElementById('retrieve-message-form');
    if (retrieveForm) {
        retrieveForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const password = document.getElementById('retrieve-password').value;
            const lockerId = retrieveForm.querySelector('input[name="locker_id"]').value;
            
            // 验证密码
            if (!/^\d{6}$/.test(password)) {
                showError(retrieveForm, '密码必须是6位数字');
                return;
            }
            
            // 显示加载状态
            const submitBtn = retrieveForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 获取中...';
            
            try {
                const response = await fetch('/retrieve_from_locker', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        locker_id: lockerId,
                        password: password
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 显示消息内容
                    document.getElementById('message-content-view').textContent = data.content;
                    document.getElementById('retrieved-locker-name').textContent = data.locker_name;
                    
                    // 隐藏表单，显示结果
                    document.querySelector('.locker-tabs').classList.add('hidden');
                    document.getElementById('retrieve-result-card').classList.remove('hidden');
                } else {
                    showError(retrieveForm, data.error || '获取消息失败，请检查密码');
                }
            } catch (error) {
                showError(retrieveForm, '发生错误，请重试');
                console.error('Error:', error);
            } finally {
                // 重置按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            }
        });
    }
    
    // 复制消息按钮
    const copyMessageBtn = document.getElementById('copy-message-btn');
    if (copyMessageBtn) {
        copyMessageBtn.addEventListener('click', () => {
            const messageContent = document.getElementById('message-content-view').textContent;
            navigator.clipboard.writeText(messageContent).then(() => {
                const originalText = copyMessageBtn.innerHTML;
                copyMessageBtn.innerHTML = '<i class="fas fa-check"></i> 已复制';
                
                setTimeout(() => {
                    copyMessageBtn.innerHTML = originalText;
                }, 2000);
            });
        });
    }
    
    // 返回按钮
    const backToLockerBtn = document.getElementById('back-to-locker-btn');
    if (backToLockerBtn) {
        backToLockerBtn.addEventListener('click', () => {
            document.getElementById('retrieve-result-card').classList.add('hidden');
            document.querySelector('.locker-tabs').classList.remove('hidden');
            document.getElementById('retrieve-password').value = '';
            // 刷新页面以更新容量
            location.reload();
        });
    }
    
    // 存储新消息按钮
    const storeNewBtn = document.getElementById('store-new-btn');
    if (storeNewBtn) {
        storeNewBtn.addEventListener('click', () => {
            document.getElementById('store-result-card').classList.add('hidden');
            document.querySelector('.locker-tabs').classList.remove('hidden');
            storeForm.reset();
            // 刷新页面以更新容量
            location.reload();
        });
    }
    
    // 显示错误信息
    function showError(form, message) {
        // 检查是否已存在错误元素
        let errorElement = form.querySelector('.error-message');
        
        if (!errorElement) {
            // 创建错误元素
            errorElement = document.createElement('div');
            errorElement.className = 'error-message';
            errorElement.style.color = 'var(--error-color)';
            errorElement.style.padding = '0.75rem';
            errorElement.style.marginTop = '1rem';
            errorElement.style.backgroundColor = 'rgba(245, 34, 45, 0.1)';
            errorElement.style.borderRadius = '0.25rem';
            errorElement.style.borderLeft = '3px solid var(--error-color)';
            
            // 添加到表单
            form.appendChild(errorElement);
        }
        
        // 设置消息
        errorElement.textContent = message;
        
        // 一段时间后移除
        setTimeout(() => {
            errorElement.style.display = 'none';
            setTimeout(() => {
                errorElement.remove();
            }, 300);
        }, 5000);
    }
});
